package com.ruoyi.article.controller;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.article.domain.ZRelationArticleLabel;
import com.ruoyi.article.mapper.ZArticleMapper;
import com.ruoyi.article.service.IZRelationArticleLabelService;
import com.ruoyi.article.service.impl.ZRelationArticleLabelServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.article.domain.ZArticle;
import com.ruoyi.article.service.IZArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 文章Controller
 * 
 * @author ruoyi
 * @date 2024-10-24
 */
@RestController
@RequestMapping("/article/article")
public class ZArticleController extends BaseController
{
    @Autowired
    private IZArticleService zArticleService;
    @Autowired
    private IZRelationArticleLabelService zRelationArticleLabelService;

    /**
     * 查询文章列表
     */
    @PreAuthorize("@ss.hasPermi('article:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZArticle zArticle)
    {
        List<ZArticle> list = zArticleService.selectArticleAll(zArticle);

        return getDataTable(list);
    }

    /**
     * 导出文章列表
     */
    @PreAuthorize("@ss.hasPermi('article:article:export')")
    @Log(title = "文章", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZArticle zArticle)
    {
        List<ZArticle> list = zArticleService.list(new QueryWrapper<ZArticle>(zArticle));
        ExcelUtil<ZArticle> util = new ExcelUtil<ZArticle>(ZArticle.class);
        util.exportExcel(response, list, "文章数据");
    }

    /**
     * 获取文章详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:article:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(zArticleService.getByIdArticle(id));
    }

    /**
     * 新增文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:add')")
    @Log(title = "文章", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZArticle zArticle)
    {
        return toAjax(zArticleService.insertZArticle(zArticle));
    }

    /**
     * 修改文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:edit')")
    @Log(title = "文章", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZArticle zArticle) throws UnknownHostException {
        return toAjax(zArticleService.updateZArticle(zArticle));
    }

    /**
     * 删除文章
     */
    @PreAuthorize("@ss.hasPermi('article:article:remove')")
    @Log(title = "文章", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        //删除文章与标签的数据
        LambdaQueryWrapper<ZRelationArticleLabel> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ZRelationArticleLabel::getArticleId,ids);
        zRelationArticleLabelService.remove(wrapper);
        return toAjax(zArticleService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 根据文章id，新增文章内容
     */
    @PostMapping("/updateArticleById")
    public AjaxResult updateArticleById(@RequestBody ZArticle zArticle)
    {
        return toAjax(zArticleService.updateArticleById(zArticle));
    }


    /**
     * 爬取文章详细信息
     */
    @GetMapping(value = "/python")
    public AjaxResult getArticlePython(){
        try {
            // 读取 JSON 文件
            List<Map<String, String>> jsonList = readJsonFile("C:\\Users\\admin\\Desktop\\project\\python\\pythonProject\\csdn\\csdn\\spiders\\java_.json");
            processJsonList(jsonList);
        } catch (IOException e) {
            System.err.println("处理 JSON 文件时出现错误: " + e.getMessage());
        }
        return AjaxResult.success();
    }


    // 读取 JSON 文件的方法
    private static List<Map<String, String>> readJsonFile(String filePath) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(new File(filePath), List.class);
    }

    // 处理 JSON 列表的方法
    private  void processJsonList(List<Map<String, String>> jsonList) throws IOException {
        for (Map<String, String> jsonMap : jsonList) {
            System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
            String title = jsonMap.get("title");
            String articleUrl = jsonMap.get("url");
            String articlesList = jsonMap.get("articles_list");
            //保存文章
            saveArticle(title, articleUrl, articlesList);

        }
    }

    @Autowired
    private ZArticleMapper zArticleMapper;
    @Autowired
    private com.ruoyi.article.service.impl.ZRelationArticleLabelServiceImpl ZRelationArticleLabelServiceImpl;

    @Transactional
    public void saveArticle(String title, String articleUrl, String articlesList) {
        {
            ZArticle zArticle = new ZArticle();
            zArticle.setCreateTime(DateUtils.getNowDate());
            zArticle.setAuthorId(1L);
            zArticle.setAuthor("admin");
            zArticle.setStatus("0");
            zArticle.setIsTop("1");
            zArticle.setImg("/profile/upload/csdn.jpg");
            zArticle.setTitle(title);
            zArticle.setArticleUrl(articleUrl);
            zArticle.setSendTime(DateUtils.getNowDate());
            zArticle.setContent(articlesList);


            //维护文章与文章标签的关系

            zArticle.setArticleLabel("java");
            zArticleMapper.insert(zArticle);
            Long articleId = zArticle.getId();

            //保存文章与标签关系表
            ZRelationArticleLabel zRelationArticleLabel = new ZRelationArticleLabel();
            zRelationArticleLabel.setArticleId(articleId);
            zRelationArticleLabel.setLabelId(5L);
            zRelationArticleLabel.setArticleTitle(title);
            zRelationArticleLabel.setLabelName("java");
            //0已发布，1待发布
            zRelationArticleLabel.setArticleStatus("0");

            ZRelationArticleLabelServiceImpl.save(zRelationArticleLabel);
        }

    }
}
